package org.example.strategypatterndemo.Strategy.controller;

import org.example.strategypatterndemo.Strategy.OrderContext;
import org.example.strategypatterndemo.Strategy.PromotionStrategyFactory;
import org.example.strategypatterndemo.module1.service.PromotionStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * PromotionController
 * @author dingchen
 * @version 2025/05/29 19:42
**/
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/promotion")
public class PromotionController {

    @Autowired
    private OrderContext orderContext;

    @Autowired
    private PromotionStrategyFactory strategyFactory;

    @GetMapping("/calculate")
    public ResponseEntity<Map<String, Object>> calculate(@RequestParam double orderAmount, @RequestParam String strategyType) {
        try {
            // 1. 从工厂获取策略实例
            PromotionStrategy strategy = strategyFactory.createStrategy(strategyType);

            // 2. 上下文应用策略
            orderContext.changeStrategy(strategy);

            // 3. 执行计算
            double finalPrice = orderContext.calculateFinalPrice(orderAmount);

            // 4. 构建响应
            Map<String, Object> result = new LinkedHashMap<>();
            result.put("开始价格", orderAmount);
            result.put("折扣类型", strategyType);
            result.put("最后的折扣", finalPrice);

            return ResponseEntity.ok(result);

        } catch (IllegalArgumentException e) {
            // 处理未知策略类型的情况
            Map<String, Object> error = new LinkedHashMap<>();
            error.put("error", "INVALID_STRATEGY");
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}
